package com.example.servlet;

import com.example.dao.NovelDao;
import com.example.dao.UserDao;
import com.example.domain.Novel;
import com.example.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet("/AdminUserUpdateServlet")
public class AdminUserUpdateServlet extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request,response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("utf-8");
        UserDao userDao = new UserDao();
        int affectedRow = 0;
        HttpSession session = request.getSession();
        int user_id = Integer.parseInt(request.getParameter("user_id"));
        User  user = userDao.getUserById(user_id);
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repeatPassword = request.getParameter("repeatPassword");
        String email = request.getParameter("email");
        String isAdmin = request.getParameter("isAdmin");
        boolean flag = userDao.checkUsername(username);

        if ((!user.getUsername().equals(username)) && flag){
            request.setAttribute("msg","用户名存在,修改失败！");
            request.getRequestDispatcher("admin_UserUpdate.jsp").forward(request,response);
            return;
        }
        if(!password.equals(repeatPassword)){
            request.setAttribute("msg","两次密码不一致，请重新输入！");
            request.getRequestDispatcher("admin_UserUpdate.jsp").forward(request,response);
            return;
        }
        if((!user.getEmail().equals(email)) && userDao.checkEmail(email)){
            request.setAttribute("msg","邮箱已存在,修改失败！");
            request.getRequestDispatcher("admin_UserUpdate.jsp").forward(request,response);
            return;
        }
        if (isAdmin.equals("true")){
            affectedRow = userDao.adminUpdateUserInfo(new User(user_id,username,password,email,true));
        }else {
            affectedRow = userDao.adminUpdateUserInfo(new User(user_id,username,password,email,false));
        }
        if(affectedRow==0){
            request.setAttribute("msg","修改失败！！");
            request.getRequestDispatcher("admin_UserUpdate.jsp").forward(request,response);
        }
        session.setAttribute("userTemp",userDao.getUserById(user_id));
        request.setAttribute("msg","修改成功！！");
        request.getRequestDispatcher("admin_UserUpdate.jsp").forward(request,response);
    }
}
